﻿using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;

namespace FGUFW.Core
{
    static public class IPAddressUtility
    {
        static IPAddress _ipv4;
        static public IPAddress IPv4
        {
            get
            {
                if(_ipv4==null)
                {
                    _ipv4 = getIPv4();
                }
                return _ipv4;
            }
        }

        static IPAddress _ipv6;
        static public IPAddress IPv6
        {
            get
            {
                if(_ipv6==null)
                {
                    _ipv6 = getIPv6();
                }
                return _ipv6;
            }
        }

        static IPAddress getIPv4()
        {
            IPAddress output=null;

            foreach (NetworkInterface item in NetworkInterface.GetAllNetworkInterfaces())
            {
    #if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN
                NetworkInterfaceType _type1 = NetworkInterfaceType.Wireless80211;
                NetworkInterfaceType _type2 = NetworkInterfaceType.Ethernet;

                if ((item.NetworkInterfaceType == _type1 || item.NetworkInterfaceType == _type2) && item.OperationalStatus == OperationalStatus.Up)
    #endif 
                {
                    foreach (UnicastIPAddressInformation ip in item.GetIPProperties().UnicastAddresses)
                    {
                        if (ip.Address.AddressFamily == AddressFamily.InterNetwork)
                        {
                            output = ip.Address;
                        }
                    }
                }
            }
            return output;
        }

        static IPAddress getIPv6()
        {
            if (!Socket.OSSupportsIPv6)
            {
                return null;
            }

            IPAddress output=null;

            foreach (NetworkInterface item in NetworkInterface.GetAllNetworkInterfaces())
            {
    #if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN
                NetworkInterfaceType _type1 = NetworkInterfaceType.Wireless80211;
                NetworkInterfaceType _type2 = NetworkInterfaceType.Ethernet;

                if ((item.NetworkInterfaceType == _type1 || item.NetworkInterfaceType == _type2) && item.OperationalStatus == OperationalStatus.Up)
    #endif 
                {
                    foreach (UnicastIPAddressInformation ip in item.GetIPProperties().UnicastAddresses)
                    {
                        if (ip.Address.AddressFamily == AddressFamily.InterNetworkV6)
                        {
                            output = ip.Address;
                        }
                    }
                }
            }
            return output;
        }
        


    }
}